package com.artezio.vacation.dao.hibernate;

import com.artezio.vacation.dao.EntityDAO;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Support object for hibernate dao.
 * Implement basic operations like select, update, delete.
 */
public class HibernateEntityDAOSupport<T> implements EntityDAO<T> {

    /**
     * All subclasses should provide domain object class.
     * Used for finding objects by id
     */
    private Class<T> objClass;
    private SessionFactory sessionFactory;

    public HibernateEntityDAOSupport(Class<T> objClass, SessionFactory sessionFactory) {
        this.objClass = objClass;
        this.sessionFactory = sessionFactory;
    }

    @Override
    public T find(long id) {
        return (T) sessionFactory.getCurrentSession().get(objClass, id);
    }

    @Override
    public void saveOrUpdate(T obj) {
        sessionFactory.getCurrentSession().saveOrUpdate(obj);
    }

    @Override
    public void delete(T obj) {
        sessionFactory.getCurrentSession().delete(obj);
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
